package com.mvp.method2.retrofit;

import android.util.Log;

import io.reactivex.observers.DisposableObserver;
import retrofit2.HttpException;

/**
 * Created by Administrator on 2019/3/6.
 */

public abstract class HttpObserver<T> extends DisposableObserver<T> {

    private static final String TAG = "HttpObserver";

    @Override
    public void onNext(T t) {
        onSuccess(t);
    }

    @Override
    public void onError(Throwable e) {
        e.printStackTrace();
        if (e instanceof HttpException) {
            HttpException httpException = (HttpException) e;
            //httpException.response().errorBody().string()
            int code = httpException.code();
            String msg = httpException.getMessage();
            Log.d(TAG, "code=" + code);
            if (code == 504) {
                msg = "网络不给力";
            }
            if (code == 502 || code == 404) {
                msg = "服务器异常，请稍后再试";
            }
            onFailure(msg);
        } else {
            onFailure(e.getMessage());
        }
        onFinish();
    }

    @Override
    public void onComplete() {
        onFinish();
    }

    public abstract void onSuccess(T t);

    public abstract void onFailure(String msg);

    public abstract void onFinish();
}
